package c04.biasedlock;

import lombok.extern.slf4j.Slf4j;
import org.openjdk.jol.info.ClassLayout;

import java.util.Vector;
import java.util.concurrent.locks.LockSupport;

/*
批量撤销

偏向锁默认是延迟生效的，程序启动时不会立即生效，如果想避免延迟，可以加VM参数禁用延迟：
-XX:BiasedLockingStartupDelay=0

偏向锁适用于很少发生竞态条件的情况，对于确定一般情况下都会发生竞态条件的应用场景，可以禁用偏向锁
-XX:-UseBiasedLocking
 */
@Slf4j(topic = "c.BatchBiasedRevoke")
public class BatchBiasedRevoke {
    static class Dog {

    }

    static Thread t1,t2,t3;

    public static void main(String[] args) throws InterruptedException {
        Vector<Dog> list = new Vector<>();

        int loopNumber = 40;
        t1 = new Thread(() -> {
            for (int i = 1; i < loopNumber; i++) {
                Dog d = new Dog();
                list.add(d);
                synchronized (d) {
                    log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintable());
                }
            }
            LockSupport.unpark(t2);
        }, "t1");
        t1.start();

        t2 = new Thread(() -> {
            LockSupport.park();
            log.debug("===============> ");
            for (int i = 1; i < loopNumber; i++) {
                Dog d = list.get(i);
//                log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true));
                log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintable());
                synchronized (d) {
//                    log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true));
                    log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintable());
                }
//                log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true));
                log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintable());
            }
            LockSupport.unpark(t3);
        }, "t2");
        t2.start();

        t3 = new Thread(() -> {
            LockSupport.park();
            log.debug("===============> ");
            for (int i = 1; i < loopNumber; i++) {
                Dog d = list.get(i);
//                log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true));
                log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintable());
                synchronized (d) {
//                    log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true));
                    log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintable());
                }
//                log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple(true));
                log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintable());
            }
        }, "t3");
        t3.start();

        t3.join();
//        log.debug(ClassLayout.parseInstance(new Dog()).toPrintableSimple(true));
        log.debug(ClassLayout.parseInstance(new Dog()).toPrintable());
    }
}

